using System;
using System.Collections;
using System.Xml.Linq;

// 定义观察者接口
public interface IObserver
{
    void Update();
}

// 定义主题接口
public interface ISubject
{
    void Attach(IObserver observer);
    void Detach(IObserver observer);
    void NotifyObservers();
    IEnumerable GetObservers();
}

// 具体主题类
public class ConcreteSubject : ISubject
{
    private string _state;
    private ArrayList _observers = new ArrayList();

    public void Attach(IObserver observer)
    {
        if (!_observers.Contains(observer))
        {
            _observers.Add(observer);
        }
    }

    public void Detach(IObserver observer)
    {
        _observers.Remove(observer);
    }

    public void NotifyObservers()
    {
        foreach (IObserver observer in _observers)
        {
            observer.Update();
        }
    }

    public IEnumerable GetObservers()
    {
        return _observers;
    }

    public void Change()
    {
        _state = "State changed";
        Console.WriteLine("Subject changed state to: " + _state);
        NotifyObservers();
    }
}

// 具体观察者类
public class ConcreteObserver : IObserver
{
    public void Update()
    {
        Console.WriteLine("Observer updated with new state.");
    }
}

// 客户端代码
public class Client
{
    public static void Main()
    {
        ConcreteSubject subject = new ConcreteSubject();
        IObserver observer1 = new ConcreteObserver();
        IObserver observer2 = new ConcreteObserver();

        subject.Attach(observer1);
        subject.Attach(observer2);

        subject.Change();
    }
}

//输出结果
//Subject changed state to: State changed
//Observer updated with new state.
//Observer updated with new state.